package com.tanhua.server.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class UserService {

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private RestTemplate restTemplate;

    private static final ObjectMapper objectMapper=new ObjectMapper();

    /**
     * 在my-tanhua-server请求sso系统校验token,得到user对象
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        //定义请求到sso的url(拿到配置未见中的url与token进行拼接),就是访问sso中的UserController
        String url=ssoUrl+"/user/"+token;
        try {
            //使用restTemplate的getForObject得到json,类型为字符串
            String data=restTemplate.getForObject(url,String.class);
            if(StringUtils.isEmpty(data)){
                return null;
            }
            return objectMapper.readValue(data,User.class);
        } catch (Exception e) {
            log.error("校验token出错，token="+token);
        }
        return null;
    }
}
